package com.ffsky.cordova.plugin;

import android.webkit.ValueCallback;

import com.ffsky.jsplugin.ExposedJsApi;
import com.ffsky.logger.L;

import org.apache.cordova.CordovaWebView;

public class ExposedJsApiImpl implements ExposedJsApi {

    private CordovaWebView mCordovaWebView;
    final String TAG = "ExposedJsApiImpl";
    private boolean disposeState = false;
    public ExposedJsApiImpl(CordovaWebView cordovaWebView) {
        mCordovaWebView = cordovaWebView;
        L.i(TAG, "new...");
    }

    @Override
    public void evaluateJavascript(String js) {
        if(disposeState){
            return;
        }
        L.i(TAG, "evaluateJavascript->", js);
        if (mCordovaWebView != null) {
            mCordovaWebView.getEngine().evaluateJavascript(js, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    L.i(TAG, "onReceiveValue->", js);
                }
            });
        }
    }

    @Override
    public String getWebViewUrl() {
        if(mCordovaWebView!=null){
            return mCordovaWebView.getUrl();
        }
        return null;
    }

    @Override
    public void dispose() {
        disposeState = true;
        L.i(TAG, "dispose.");
        mCordovaWebView = null;
    }
}
